package com.farmer.controller;

import com.farmer.utils.CommonUtil;
import com.farmer.utils.MD5Util;
import com.farmer.utils.Result;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RequestMapping("captcha")
@RestController
public class CaptchaController {
    @Autowired
    private Producer captchaProducer;
    @Autowired
    private RedisTemplate redisTemplate;
//    获取验证码
    @GetMapping("get")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        生成验证码数字
        String text = captchaProducer.createText();
        redisTemplate.opsForValue().set(getCaptchaKey(request),text,30, TimeUnit.SECONDS);
//        生成验证码图片
        BufferedImage image = captchaProducer.createImage(text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"png",outputStream);
        outputStream.flush();
        outputStream.close();
    }
//    校验验证码
    @GetMapping("check")
    public Result checkCaptcha(String captcha, HttpServletRequest request){
        Object value = redisTemplate.opsForValue().get(getCaptchaKey(request));
        if (value==null){
            return Result.build(null,222,"验证码已过期");
        }
        if (captcha.equals(value)){
            return Result.build(null,200,"验证成功");
        }
        return Result.build(null,222,"验证失败，验证码错误");
    }

    private String getCaptchaKey(HttpServletRequest request){
        String ipAddr = CommonUtil.getIpAddr(request);
        String userInfo = request.getHeader("User-Agent");
        String md5 = CommonUtil.MD5(ipAddr + userInfo);
        return "captcha:"+md5;
    }
}